package multiThread;

/*
 * MultiThread: Train example
 * With thread synchronization, with wait() & with notify()
 */

class Train0 implements Runnable {
	synchronized public void run() {
		Thread t = Thread.currentThread();
		String name = t.getName();
		for (int i = 0; i < 20; i++) {
			if (name.equals("Raj") && i == 5) try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (name.equals("Geetha") && i == 7) notify();
			System.out.println(Thread.currentThread().getName() + " = " + i);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
	}
}

/*
 * With thread synchronization, with wait() & with notifyAll()
 */

class Train1 implements Runnable {
	synchronized public void run() {
		Thread t = Thread.currentThread();
		String name = t.getName();
		for (int i = 0; i < 20; i++) {
			if (name.equals("Raj") && i == 5) try {
				wait();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			if (name.equals("Sita") && i == 5) try {
				wait();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			if (name.equals("Geetha") && i == 7) {
				notifyAll();
			}

			System.out.println(Thread.currentThread().getName() + " = " + i);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
	}
}

/*
 * With thread synchronization, with wait() & without notify()
 */

class Train2 implements Runnable {
	synchronized public void run() {
		Thread t = Thread.currentThread();
		String name = t.getName();
		for (int i = 0; i < 20; i++) {
			if (name.equals("Raj") && i == 5) try {
				wait();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + " = " + i);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
	}
}

/*
 * With thread synchronization, without wait() & without notify() code pending
 */
class Train3 implements Runnable {
	synchronized public void run() {
		Thread t = Thread.currentThread();
		@SuppressWarnings("unused")
		String name = t.getName();
		for (int i = 0; i < 20; i++) {
			System.out.println(Thread.currentThread().getName() + " = " + i);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
	}
}

public class MyThread10 {
	public static void main(String args[]) {
		Train2 obj1 = new Train2();

		// Creation of thread.
		Thread t1 = new Thread(obj1);
		Thread t2 = new Thread(obj1);
		Thread t3 = new Thread(obj1);

		t1.setName("Raj");
		t2.setName("Geetha");
		t3.setName("Sita");

		// Thread is made runnable.
		t1.start();
		t2.start();
		t3.start();
	}
}